﻿using System;
using System.ComponentModel;
using GpgApi;

namespace WgpgCore
{
    public sealed class Task : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public TaskStatus Status { get; private set; }
        public String Name { get; private set; }
        public String Description { get; private set; }

        private GpgInterface _gpg;

        public void Abort()
        {
            if (_gpg != null)
                _gpg.Abort();
        }

        internal Task(GpgInterface gpg, String name, String description)
        {
            if (gpg == null)
                throw new ArgumentNullException("gpg");

            _gpg = gpg;
            _gpg.GpgInterfaceEvent += GpgInterfaceEvent;

            Status = TaskStatus.NotStarted;
            Name = name;
            Description = description;
        }

        internal Boolean IsSame(GpgInterface gpg)
        {
            return Object.ReferenceEquals(_gpg, gpg);
        }

        private void GpgInterfaceEvent(Object sender, GpgInterfaceResult result)
        {
            if (result.Status == GpgInterfaceStatus.Started)
            {
                Status = TaskStatus.Running;
            }
            else if (result.Status != GpgInterfaceStatus.Processing)
            {
                switch (result.Status)
                {
                    case GpgInterfaceStatus.Success: Status = TaskStatus.Success; break;
                    case GpgInterfaceStatus.Error: Status = TaskStatus.Error; break;
                }

                _gpg = null;
            }

            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("Status"));
        }
    }
}
